package ast

type AndOr struct {
	Children []interface{}
	IsAnd    bool
}

func NewAnd() *AndOr {
	return NewAndOr(true)
}
func NewOr() *AndOr {
	return NewAndOr(false)
}
func NewAndOr(isAnd bool) *AndOr {
	ins := &AndOr{
		IsAnd: isAnd,
	}
	ins.Children = make([]interface{}, 0)
	return ins
}

func (t *AndOr) addMap(mp map[string]interface{}) (interface{}, error) {
	for k, v := range mp {
		item, err := parsePair(k, v)
		if err != nil {
			return nil, err
		}
		if item != nil {
			t.Children = append(t.Children, item)
		}
	}
	switch len(t.Children) {
	case 0:
		return nil, nil
	case 1:
		return t.Children[0], nil
	default:
		return t, nil
	}
}

func (t *AndOr) addArray(arr []interface{}) (interface{}, error) {
	for _, vv := range arr {
		//vv 必定为 map
		var query map[string]interface{}
		var ok bool
		if query, ok = vv.(map[string]interface{}); !ok {
			continue
		}
		item, err := parseMap(query, true)
		if err != nil {
			return nil, err
		}
		if item != nil {
			t.Children = append(t.Children, item)
		}
	}
	switch len(t.Children) {
	case 0:
		return nil, nil
	case 1:
		return t.Children[0], nil
	default:
		return t, nil
	}
}
